
<template>
  <div>
    <div>
      <img id="image" :src="imgurl" alt="Picture">
    </div>
    <button type="button" id="button" @click="crop">确定</button>
  </div>
</template>
<script>
import Cropper from 'cropperjs'
import '../../../static/plug/cropper/cropper.css'
export default {
  data () {
    return {
      cropper: '',
      upimg: '',
      croppable: false
    }
  },
  props: {
    imgurl: {
      type: String,
      default: ''
    },
    wh: {
      type: String,
      default: '1'
    }
  },
  watch: {
    imgurl (newValue, oldVaule) {
    // 每次替换图片要重新得到新的url
      if (this.cropper) {
        this.cropper.replace(newValue)
      }
    }

  },
  computed: {

  },
  methods: {
    crop () {
      var croppedCanvas
      if (!this.croppable) {
        return
      }
      croppedCanvas = this.cropper.getCroppedCanvas()
      this.cutimg = croppedCanvas.toDataURL()
      this.$emit('getcutimg', { cutimg: this.cutimg, hasimg: true })
    }
  },
  mounted () {
    var self = this
    var image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      aspectRatio: self.wh,
      viewMode: 1,
      background: false,
      zoomable: false,
      ready: function () {
        self.croppable = true
      }
    })
  }
}
</script>

<style>
#image {
  max-width: 100%;
}
#button {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 80px;
  height: 40px;
  border:none;
  border-radius: 5px;
  background:white;
}
</style>
